package com.cman777.springc.common.helper;

import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author chenzhicong
 * @time 2020/1/20 15:46
 * @description  一些BigDecimal用于统计的一些方法
 */
public class MathStatisticsUtil {


    /**
     * 计算集合的和
     */
    public static BigDecimal listSum(List<BigDecimal> list) {
        BigDecimal sum = new BigDecimal(0);
        for (BigDecimal bigDecimal : list) {
            sum = sum.add(bigDecimal);
        }
        return sum;
    }

    /**
     * 计算集合的平均值
     */
    public static BigDecimal listAvg(List<BigDecimal> list, int scale) {
        if(CollectionUtils.isEmpty(list)){
            return new BigDecimal(0).setScale(scale,RoundingMode.HALF_UP);
        }
        return listSum(list).divide(new BigDecimal(list.size()), scale, RoundingMode.HALF_UP);
    }


    /**
     * 计算中位数
     */
    public static BigDecimal midValue(List<BigDecimal> listParam,boolean isSorted,int scale) {
        if(CollectionUtils.isEmpty(listParam)){
            return new BigDecimal(0).setScale(scale,RoundingMode.HALF_UP);
        }
        List<BigDecimal> list = null;
       if(!isSorted){
           //为了顺序的安全copy一个list
           list = new ArrayList(list);
           Collections.sort(list);
       }else{
           list = listParam;
       }
       int listSize = list.size();
       if(1 == (listSize & 1)){
            return list.get((listSize - 1) >> 1);
       }else{
           return list.get((listSize >> 1) - 1).add(list.get(listSize >> 1)).divide(new BigDecimal(2),scale,RoundingMode.HALF_UP);
       }
    }







}
